function showPage(pageId) {
    const pages = document.querySelectorAll('.page');
    pages.forEach(page => {
        page.style.display = 'none';
    });
    if (pageId === 'main') {
        const mainButtons = document.querySelector('.main-buttons');
        mainButtons.style.display = 'block';
    } else {
        const mainButtons = document.querySelector('.main-buttons');
        mainButtons.style.display = 'none';
        const page = document.getElementById(pageId);
        page.style.display = 'block';
    }
}

function createOrder() {
    const startLat = document.getElementById('start-lat').value;
    const startLng = document.getElementById('start-lng').value;
    const endLat = document.getElementById('end-lat').value;
    const endLng = document.getElementById('end-lng').value;
    const typeChoice = document.getElementById('order-type').value;

    const data = {
        startLat,
        startLng,
        endLat,
        endLng,
        typeChoice
    };

    fetch('/api/orders', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(order => {
            const resultDiv = document.getElementById('order-result');
            if (order) {
                const startTime = new Date(order.startTime).toLocaleString();
                resultDiv.innerHTML = `订单创建成功！订单编号：${order.id}<br>预估费用：${order.totalFare}元<br>打车起始时间：${startTime}`;
                if (order.assignedVehicle) {
                    resultDiv.innerHTML += `<br>已为您匹配车辆：${order.assignedVehicle.licensePlate}`;
                } else {
                    resultDiv.innerHTML += '<br>当前无可用车辆';
                }
                // 轮询检查订单状态
                const intervalId = setInterval(() => {
                    fetch(`/api/orders/${order.id}`)
                        .then(response => response.json())
                        .then(updatedOrder => {
                            if (updatedOrder.status === 'COMPLETED') {
                                const endTime = new Date(updatedOrder.endTime).toLocaleString();
                                resultDiv.innerHTML += `<br>行程已结束，结束时间：${endTime}`;
                                clearInterval(intervalId);
                            }
                        });
                }, 5000);
            } else {
                resultDiv.innerHTML = '当前无可用车辆';
            }
        })
        .catch(error => {
            console.error('下单失败:', error);
            const resultDiv = document.getElementById('order-result');
            resultDiv.innerHTML = '下单失败，当前无可用车辆';
        });
}

function viewOrderStatus() {
    const orderId = document.getElementById('order-id').value;

    fetch(`/api/orders/${orderId}`)
        .then(response => response.json())
        .then(order => {
            const resultDiv = document.getElementById('order-status-result');
            if (order) {
                const startTime = order.startTime ? new Date(order.startTime).toLocaleString() : '无';
                const endTime = order.endTime ? new Date(order.endTime).toLocaleString() : '无';
                resultDiv.innerHTML = `订单编号：${order.id}<br>订单状态：${order.status}<br>打车起始时间：${startTime}<br>行程结束时间：${endTime}`;
                if (order.assignedVehicle) {
                    resultDiv.innerHTML += `<br>匹配车辆：${order.assignedVehicle.licensePlate}`;
                }
                resultDiv.innerHTML += `<br>预估费用：${order.totalFare}元`;
            } else {
                resultDiv.innerHTML = '未找到该订单。';
            }
        })
        .catch(error => {
            console.error('查询订单失败:', error);
            const resultDiv = document.getElementById('order-status-result');
            resultDiv.innerHTML = '查询订单失败，请稍后重试';
        });
}

function applyForJoining() {
    const name = document.getElementById('driver-name').value;
    const licenseNumber = document.getElementById('license-number').value;
    const vehicleLicensePlate = document.getElementById('vehicle-license-plate').value;
    const model = document.getElementById('model').value;
    const type = document.getElementById('type').value;
    const seats = document.getElementById('seats').value;
    const canCarpool = document.getElementById('can-carpool').checked;

    const data = {
        name,
        licenseNumber,
        vehicleLicensePlate,
        model,
        type,
        seats,
        canCarpool
    };

    fetch('/api/drivers', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.text())
        .then(message => {
            const resultDiv = document.getElementById('join-result');
            resultDiv.innerHTML = message;
        })
        .catch(error => {
            console.error('加盟申请失败:', error);
            const resultDiv = document.getElementById('join-result');
            resultDiv.innerHTML = '加盟申请失败，请稍后重试';
        });
}
